package com.wz.compilerManual;

import com.wz.compilerManual.add.symbol.*;
import com.wz.compilerManual.tree.Node;
import com.wz.compilerManual.tree.ParseTree;
import com.wz.compilerManual.tree.PredicateTable;

/**
 * 伪代码:
 * tokens[];
 * i=0;
 * stack = [s];
 * while (stack != []){
 * if (stack[top] is a terminal t){
 * if (t == token[i++]){
 * pop();
 * } else {
 * error!
 * }
 * } else if (stack[top] is a nonterminal t){
 * pop();
 * push(the correct table[n, t] right hand side of T);
 * }
 * }
 */
public class CompilerMachine {

    private static Node root;

    public static ParseTree analysis(String s) {
        char[] tokens = s.toCharArray();
        int i = 0;
        Node root = new Node(new S_E());
        root.setRightBrother(new Node(new S_epsilon()));
        ParseTree parseTree = new ParseTree(root);

        while (!parseTree.peek().isEndPoint()) {
            Node node = parseTree.peek();
            if (node.getSymbol().isTerminal()) {
                if (node.getSymbol().match(String.valueOf(tokens[i]))) {
                    System.out.println(tokens[i] + " 匹配");
                    node.setData(String.valueOf(tokens[i]));
                    i = i + 1;
                    parseTree.pop();
                } else {
                    System.out.println("对:" + tokens[i] + " 解析失败!");
                }
            } else {
                ProductionFormula formula = PredicateTable.getProductionFormula(node.getSymbol(), String.valueOf(tokens[i]));
                pushProductFormulaToParseTree(formula, parseTree);
            }
        }
        return parseTree;
    }

    private static void pushProductFormulaToParseTree(ProductionFormula formula, ParseTree parseTree) {
        for (Symbol symbol : formula.getRight()) {
            if (symbol instanceof S_epsilon) {
                parseTree.pop();
                return;
            }
        }
        parseTree.push(formula.getRight());
    }

    public static void main(String[] args) {
        ParseTree parseTree = CompilerMachine.analysis("12+34+56$");
        System.out.println("111");
    }
}